﻿using Xejen.Communication.Socket.Abstract;
using Xejen.Communication.Socket.Configuration;
using Xejen.Communication.Socket.Extensions;
using Xejen.Hosting;
using Xejen.Logger;
using Xejen.Logger.NLog;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Xejen.Communication.Socket.Client.EventTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            ILoggerManager loggerManager = NLogManager.Instance();
            ConsoleAppHost host = new ConsoleAppHost(new HostConfiguration { }, loggerManager);

            #region 构建Socket通讯
            host
                .UseSocketCommunication((builder) =>
                {
                    builder.ConfigureSocketConfiguration((config) => { }).AddCommunicator();
                })
                .Build();
            #endregion

            Service service = host.ServiceProvider.GetService(typeof(Service)) as Service;
            await service.ExecuteAsync();

            //await ExecuteAsync();

            host.Run();
        }

        static async Task ExecuteAsync()
        {
            // 指定服务器的 IP 地址和端口
            string ipAddress = "127.0.0.1";
            int port = 8080;

            // 创建 TcpClient 实例
            TcpClient tcpClient = new TcpClient();

            try
            {
                // 连接到服务器
                await tcpClient.ConnectAsync(ipAddress, port);
                Console.WriteLine($"客户端：已连接到服务器 {ipAddress}:{port}");

                // 发送数据到服务器
                string message = "Hello from client!";
                byte[] data = Encoding.UTF8.GetBytes(message);
                await tcpClient.GetStream().WriteAsync(data, 0, data.Length);

                // 在这里可以进行其他处理，如等待服务器的响应等

                // 如果需要等待服务器的响应，可以使用以下代码
                byte[] buffer = new byte[1024];
                int bytesRead = await tcpClient.GetStream().ReadAsync(buffer, 0, buffer.Length);
                string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"服务器响应: {response}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接服务器时发生错误: {ex.Message}");
            }
            finally
            {
                // 关闭客户端连接
                tcpClient.Close();
            }
        }
    }
}
